package com.global.college.utils;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;

/**
 * @author fzw
 * @date 2021/9/13 0013.
 * email：
 * description：
 */
public class FileUtils {
    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }
    public static File getSaveFile(Context context,String fileName) {
        String path = Environment.getExternalStorageDirectory().getPath() + "/" + CommonUtils.getPackageName() + "/images/";
        File file = new File(path, fileName);
        return file;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */

    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1,url.lastIndexOf("?"));
    }

    public static String getFileName(String url) {
        return url.substring(url.lastIndexOf(".") + 1);
    }

    public static Vector<String> getAllFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<String>();
        File file = new File(fileAbsolutePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File[] subFile = file.listFiles();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();
                LogUtils.w("文件名 ： " + filename);
            }
        }
        return vecFile;
    }

    /**
     * * 获取文件扩展名
     *
     * @param filename 文件名
     * @return 扩展名
     */
    public static String getFileType(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return null;
    }

    public static String createCachePath(Context context) {
        String cacheRootPath;
        if (isSdCardAvailable()) {
            // /sdcard/Android/data/<application package>/cache
            cacheRootPath = context.getExternalCacheDir().getPath();
        } else {
            // /data/data/<application package>/cache
            cacheRootPath = context.getCacheDir().getPath();
        }
        File file = new File(cacheRootPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return cacheRootPath;
    }

    /**
     * SdCard是否存在
     *
     * @return true存在
     */
    public static boolean isSdCardAvailable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 　　* 获取指定文件大小
     * 　　* @param f
     * 　　* @return
     * 　　* @throws Exception
     */
    public static long getFileSize(File file) {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                size = fis.available();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return size;
    }

    private static final String mformatType = "yyyy/MM/dd HH:mm:ss";

    public static String getFileLastModifiedTime(File file) {
        Calendar cal = Calendar.getInstance();
        long time = file.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat(mformatType);
        cal.setTimeInMillis(time);

        // 输出：修改时间[2] 2009-08-17 10:32:38
        return formatter.format(cal.getTime());
    }

    /**
     * oldPath 和 newPath必须是新旧文件的绝对路径
     */
    public static void renameFile(String oldPath, String newPath) {
        if (StringUtils.isEmpty(oldPath)) {
            return;
        }

        if (StringUtils.isEmpty(newPath)) {
            return;
        }
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);
        oldFile.renameTo(newFile);

    }

    /**
     * 删除单个文件
     *
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteSingleFile(String filePath$Name) {
        LogUtils.w("删除文件的路径:" + filePath$Name);
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                LogUtils.w("Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
                LogUtils.w("删除单个文件" + filePath$Name + "失败！");
                return false;
            }
        } else {
            LogUtils.w("删除单个文件" + filePath$Name + "不存在！");
            return false;
        }
    }


    /**
     * @Description:判断是否插入SD卡
     */
    public static boolean isHasSdcard() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
